package models;

import product.ProductSpec;
import util.common.ConvertUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liming on 16/7/16.
 * 规格产品库存
 */
@Entity
@Table(name = "admin_product_spec_stock")
public class AdminProductSpecStock extends BaseModel {
    /**
     * 仓库
     */
    @ManyToOne
    @JoinColumn(name = "admin_warehouse_id")
    public AdminWarehouse adminWarehouse;

    /**
     * 规格产品
     */
    @ManyToOne
    @JoinColumn(name = "product_spec_id")
    public ProductSpec productSpec;

    /**
     * 库存数量
     */
    @Column(name = "stock_num")
    public Double stockNum;

    /**
     * 成本单价
     */
    @Column(name = "cost_price")
    public Double costPrice;

    public AdminProductSpecStock (){

    }

    public AdminProductSpecStock (ProductSpec productSpec){
        this.productSpec = productSpec;
        this.stockNum = 0D;
        this.costPrice = 0D;
    }

    /**
     * 根据产品规格ID查询库存
     * @param productSpecId
     * @return
     */
    public static AdminProductSpecStock loadByProductSepcId(long productSpecId){
        return AdminProductSpecStock.find("productSpec.id = ?",productSpecId).first();
    }

    /**
     * 为了加载规格产品相应的库存
     * 这种写法很差
     * @param productSpecList
     * @return
     */
    public static Map<Long,AdminProductSpecStock> loadByProductSpecList(List<ProductSpec> productSpecList){
        Map<Long,AdminProductSpecStock> adminProductSpecStockMap = null;
        List<AdminProductSpecStock> adminProductSpecStockList = null;
        String productSpecIds = "";
        for(ProductSpec productSpec:productSpecList)
            productSpecIds +=  "," + productSpec.id;

        if(productSpecIds.length()>0){
            adminProductSpecStockList = AdminProductSpecStock.find("productSpec.id in (" + productSpecIds.substring(1)+ ")").fetch();
            if(adminProductSpecStockList.size()>0){
                adminProductSpecStockMap = new HashMap<>();
                for(AdminProductSpecStock adminProductSpecStock:adminProductSpecStockList){
                    adminProductSpecStockMap.put(adminProductSpecStock.productSpec.id,adminProductSpecStock);
                }
            }
        }
        return adminProductSpecStockMap;
    }


    //检查某产品是否有库存
    public static String checkStock(Integer[] ids){
        String str = "";
        String strIds = UStringUtil.concatStr(",",ids);

        List<AdminProductSpecStock> specStockList = AdminProductSpecStock.find("productSpec.id in ("+strIds+") and stockNum >0").fetch();
        for(AdminProductSpecStock specStock : specStockList){
            str += ConvertUtil.toString(specStock.productSpec.spec)+",";
        }

        return str;
    }


}
